<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Middleware;

use App\Constants\Constants;
use Hyperf\Context\Context;
use Hyperf\Contract\TranslatorInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 跨域中间件.
 */
class CorsMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        $response = $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Max-Age', 86400)
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Methods', 'POST')
            ->withHeader('Access-Control-Allow-Headers', 'Referer,Accept,DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization,Locale,Sec-Fetch-Dest,Request-Random,Request-Timestamp,Request-Platform,Request-Version,Request-Id,Request-Channel,Request-Market,Request-Version,Request-Device,Request-Simulator,Request-Uid,Request-Device-Type,Request-Package-Mark,Request-Device-Model,Request-Device-Agent,Request-Package-Name,Request-Languages');
        $languages = $request->getHeaderLine(Constants::REQUEST_LANGUAGES);
        if (empty($languages)) {
            $languages = 'en';
        }
        ApplicationContext::getContainer()->get(TranslatorInterface::class)->setLocale($languages);
        Context::set(Constants::CONTEXT_LANGUAGES, $languages);

        Context::set(ResponseInterface::class, $response);

        if (in_array($request->getMethod(), ['OPTIONS'])) {
            return $response->withStatus(204);
        }

        return $handler->handle($request);
    }
}
